var getFacebookToken = function(callback) {
    var fbUrl = 'https://graph.facebook.com/oauth/access_token';
    var params = {
        client_id: '231299333664374',
        client_secret: '438ecb9679edd8b305e04d0741b861c0',
        grant_type: 'client_credentials'
    };

    $.get(fbUrl, params, function(result) {
        var access_token = result.split('=')[1];
        localStorage.setItem('access_token', access_token);
        callback();
    });
}


var getFacebookFeed = function(callback) {
    var feedUrl = 'https://graph.facebook.com/FoundationPentruVoi/feed';
    var access_token = localStorage.getItem('access_token');
    $.get(feedUrl, {access_token: access_token}, function(result) {
        var posts = [];
        for (var i = 0; i < result.data.length; i++) {
            if (result.data[i].message){
                var post = {
                    message: result.data[i].message,
                    picture: result.data[i].picture
                };
                posts.push(post);
            }

        }
        callback(posts);
    }, 'json');
}

$.getJSON(
    'http://172.18.20.150/data/',
    function(data){
        for(var i =0; i<data.length; i++)
        {
            $("#proiecte").append(
                    '<li><a href="javascript: redirectToPosts(\''+data[i].Name+'\')"><h3>'+data[i].Title+'</h3><p>'+data[i].Description+'</p></a></li>'
            );
        }
        $('#proiecte').listview('refresh');
});

function redirectToPosts(data){
	console.log(data);
	$.mobile.changePage("#posts");
	$.getJSON(
		'http://172.18.20.150/data/'+data,
		function(data){
			var toPost = '';
			for(var i =0; i<data.length; i++)
			{
				toPost = toPost + '<li><h3>'+data[i].Title+'</h3><div>'+data[i].Content+'</div></li>';
			}
			
			$("#list_posts").html(
					toPost
			);
			$('#list_posts').listview('refresh');
	});
}

$(document).bind("mobileinit", function () {
    $.mobile.page.prototype.options.addBackBtn = true;
});

document.addEventListener("deviceready", function(){
    getFacebookToken(function(){
        getFacebookFeed(function(data) {
            for(var i =0; i<data.length; i++) {
                var html = new EJS({url: 'templates/facebook_feed.ejs'}).render({data: data});
                $("#facebook").html(html);
            }
            $('#facebook').listview('refresh');
        });

    });

});

window.fbAsyncInit = function() {
FB.init({
  appId      : '369455026468304', // App ID
  channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
  status     : true, // check login status
  cookie     : true, // enable cookies to allow the server to access the session
  xfbml      : true  // parse XFBML
});

// Additional initialization code here
};

// Load the SDK Asynchronously
(function(d){
 var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
 if (d.getElementById(id)) {return;}
 js = d.createElement('script'); js.id = id; js.async = true;
 js.src = "//connect.facebook.net/en_US/all.js";
 ref.parentNode.insertBefore(js, ref);
}(document));


FB.login(function(response) {
   if (response.authResponse) {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
       console.log('Good to see you, ' + response.name + '.');
     });
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
});

FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    // the user is logged in and has authenticated your
    // app, and response.authResponse supplies
    // the user's ID, a valid access token, a signed
    // request, and the time the access token 
    // and signed request each expire
    var uid = response.authResponse.userID;
    var accessToken = response.authResponse.accessToken;
	console.log(accessToken);
  } else if (response.status === 'not_authorized') {
    // the user is logged in to Facebook, 
    // but has not authenticated your app
  } else {
    // the user isn't logged in to Facebook.
  }
  console.log(response.status);
  
});

